package version2024.easy;

import java.util.Scanner;

/**
 * @author sunhl
 * @Description: HJ51 输出单向链表中倒数第k个结点
 * @Date: created in 2025/1/14 星期二 23:20
 * @Modified By:
 */
public class HJ51_OutputNodeFromEndOfSinglyLinkedList {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (sc.hasNext()) { // 注意 while 处理多个 case
            int n = sc.nextInt();
            ListNode head = new ListNode(-1);
            ListNode temp = head;
            for (int i = 0; i < n; i++) {
                ListNode node = new ListNode(sc.nextInt());
                temp.next = node;
                temp = temp.next;
            }
            int k = sc.nextInt();

            ListNode slow = getKthFromEnd(head, k);

            if (slow != null) {
                System.out.println(slow.val);
            } else {
                System.out.println(0);
            }
        }
    }

    // 快慢指针
    public static ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null) return null;

        ListNode fast = head, slow = head;

        //快指针先走k步
        for (int i = 0; i < k; i++) {
            if (fast == null) return fast;
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    public static class ListNode {
        ListNode next;
        int val;

        ListNode(int val) {
            this.val = val;
            next = null;
        }
    }
}


